using System.Dynamic;
using System.Linq.Expressions;
using Microsoft.Extensions.DependencyInjection;

namespace Naruto.CQRS.Command;

/// <summary>
/// 内部实现
/// </summary>
public sealed class CommandDispatcher : ICommandDispatcher
{
    /// <summary>
    /// 
    /// </summary>
    private readonly IServiceProvider _serviceProvider;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="serviceProvider"></param>
    public CommandDispatcher(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }

    /// <summary>
    /// 发送消息
    /// </summary>
    /// <param name="event"></param>
    /// <param name="cancellationToken"></param>
    public async Task SendAsync<TEvent>(TEvent @event, CancellationToken cancellationToken = default)
        where TEvent : ICommandEvent
    {
        var service =(ICommand) _serviceProvider.GetRequiredService(typeof(ICommand<>).MakeGenericType(@event.GetType()));
        await service.HandleAsync(@event, cancellationToken);
    }
}